<?php

namespace Drupal\shusy_product_purchase\Entity;

use Drupal\shusy_product_purchase\ViewsController\Traits\ShusyProductPurchaseStatusTrait;
use Entity;
use EntityFieldQuery;

class ShusyProductPurchase extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $product_id = 0;

  public $status = 0;

  use ShusyProductPurchaseStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_product_purchase');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }

    return parent::save();
  }

  function price() {
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'shusy_product_purchase_standard');
    $query->propertyCondition('product_id', $this->product_id);
    $query->propertyCondition('status', 1);
    $query->propertyOrderBy('amount', 'ASC');
    $query->propertyOrderBy('id');
    $query->range(0, 1);
    $result = $query->execute();
    if (!empty($result)) {
      foreach ($result['shusy_product_purchase_standard'] as $item) {
        return shusy_product_purchase_standard_load($item->id);
      }
    }
    return new ShusyProductPurchaseStandard();
  }
}
